package com.vote.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vote.common.entity.VoteUser;
import com.vote.common.enums.UserSessionEnum;
import com.vote.common.returns.RespCode;
import com.vote.common.returns.RespEntity;
import com.vote.common.service.VoteUserService;
import com.vote.admin.vo.param.LoginParam;
import com.vote.admin.vo.result.UserResult;
import com.vote.common.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Objects;

@Service
@Slf4j
public class VoteUserLoginService {

    @Autowired
    private VoteUserService voteUserService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 登陆
     * @param loginParam
     * @return
     */
    public RespEntity login(LoginParam loginParam, HttpSession session) {
        //校验账号和密码
        QueryWrapper<VoteUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VoteUser::getUsername, loginParam.getUsername())
                .eq(VoteUser::getPassword, loginParam.getPassword());
        VoteUser voteUser = voteUserService.getOne(queryWrapper);
        if (Objects.isNull(voteUser)) {
            return new RespEntity(RespCode.LOGIN_ERROR);
        }

        //用户数据组装
        UserResult userResult = UserResult.builder()
                .id(voteUser.getId())
                .name(voteUser.getName())
                .username(voteUser.getUsername())
                .build();

        //保存登陆会话状态
        session.setAttribute(UserSessionEnum.USER.getCode(), userResult);
        return new RespEntity(RespCode.SUCCESS);
    }

}
